package com.googlecode.chelonia;

import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.parser.JSONParser;

public class JsonServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<List<Object>> data = null;

		try {
			InputStream is = req.getInputStream();
			JSONParser parser = new JSONParser(new InputStreamReader(is, "UTF-8"));
			data = (List<List<Object>>) JSONMapper.toJava(parser.nextValue());

			if ("/AfricaMap".equals(req.getPathInfo())) {
				OutputStream out = resp.getOutputStream();
				MapImage mi = null;
				for (List<Object> sl : data) {
					String command = (String) sl.get(0);
					if ("create".equals(command)) {
						mi = new MapImage(((BigInteger) sl.get(1)).intValue(), ((BigInteger) sl.get(2)).intValue());
					} else if ("setBackground".equals(command)) {
						mi.setBackground(new Color(Integer.parseInt((String) sl.get(1), 16)));
					} else if ("paintCountries".equals(command)) {
						mi.paintCountries(new Color(Integer.parseInt((String) sl.get(1), 16)), new CountrySet(
								(String) sl.get(2)));
					} else if ("paintBorders".equals(command)) {
						mi.paintBorders(new Color(Integer.parseInt((String) sl.get(1), 16)), new CountrySet((String) sl
								.get(2)), ((BigDecimal) sl.get(3)).floatValue());
					} else if ("toImage".equals(command)) {
						mi.toImage((String) sl.get(1), out);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
	}
}
